package com.zmn.uac.business.impl.oauth.login;

import com.alibaba.fastjson.JSONObject;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.consts.GlobalConsts;
import com.zmn.saas.common.dro.app.AppInfoDRO;
import com.zmn.saas.dubbo.dto.app.AppDRO;
import com.zmn.uac.business.interfaces.channel.ChannelBService;
import com.zmn.uac.business.interfaces.oauth.login.AppleLoginBService;
import com.zmn.uac.business.template.oauth.login.BaseLoginTemplateMode;
import com.zmn.uac.common.dio.oauth.login.TempCodeDIO;
import com.zmn.uac.common.dio.oauth.login.UserAuthLoginDIO;
import com.zmn.uac.common.entity.oauth.login.*;
import com.zmn.uac.common.entity.oauth.phone.UserPhoneInfo;
import com.zmn.uac.common.info.UserAuthPhoneInfo;
import com.zmn.uac.common.info.apple.AppleUserAuthInfo;
import com.zmn.uac.util.AppleLoginUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;


/**
 * 类描述：ios登陆业务实现
 *
 * @author xujie
 * @since 2021/06/16 17:45
 */
@Slf4j
@Service
public class AppleLoginBServiceImpl extends BaseLoginTemplateMode implements AppleLoginBService {

    private static final String TAG = "ios登陆业务实现";

    private static final String DEFAULT_APPLE_AUD = "com.zmn.jtwx";

    @Resource
    private ChannelBService channelBusinessService;

    @Override
    public ResponseDTO<UserAuthLoginInfo> thirdPartyUserDataAcquisition(UserAuthLoginDIO dio, UserAuthPhoneInfo authPhoneInfo) {
        String appleAud = DEFAULT_APPLE_AUD;
        Integer channelId = dio.getChannelId();
        AppInfoDRO app = channelBusinessService.getShowAppByChannelIdOrShopId(channelId, dio.getShopId());

        if (Objects.isNull(app)) {
            return ResponseDTO.fail("查询应用为null");
        }
        UniInfo uniInfo = JSONObject.parseObject(app.getCustomFieldValue(), UniInfo.class);
        log.info("[{}], {},获取SaaS配置信息, AppInfoDRO:[{}]", TAG, dio.getUuid(), JSONObject.toJSONString(app));
        if (Objects.isNull(uniInfo)) {
            log.info("[{}]，{},应用扩展字段转换异常，customFieldValue:{}，channelId:{}，shopId:{}", TAG, dio.getUuid(), app.getCustomFieldValue(), channelId, dio.getShopId());
        } else {
            appleAud = uniInfo.getBundleId();
        }

        // 比较openId是否一致
        AppleUserAuthInfo appleUserAuthInfo = (AppleUserAuthInfo) authPhoneInfo;
        ResponseDTO<String> response = AppleLoginUtils.verifyToken(appleUserAuthInfo.getIdentityToken(), appleAud);
        if (!response.isSuccess()) {
            return ResponseDTO.fail(response.getMessage());
        }
        if (!appleUserAuthInfo.getOpenId().equals(response.getData())) {
            return ResponseDTO.fail("");
        }

        UserInfo info = setUserInfo(appleUserAuthInfo, dio);
        PlatInfo platInfo = setPlatInfo(dio, app, channelId);
        UserAuthLoginInfo userAuthLoginInfo = setUserAuthLoginInfo(app, info, platInfo);

        return ResponseDTO.success(userAuthLoginInfo);
    }

    @Override
    public ResponseDTO<String> getThirdPartyOpenIdByCode(TempCodeDIO tempCodeDIO, AppDRO app) {
        return AppleLoginUtils.verifyToken(tempCodeDIO.getCode(), DEFAULT_APPLE_AUD);
    }

    /**
     * 设置userInfo
     * @param appleUserAuthInfo
     * @param dio
     * @return
     */
    private UserInfo setUserInfo(AppleUserAuthInfo appleUserAuthInfo, UserAuthLoginDIO dio){
        return UserInfo.builder()
                .userId(null)
                .openId(appleUserAuthInfo.getOpenId())
                .unionId(appleUserAuthInfo.getOpenId())
                .type(GlobalConsts.NO)
                .realname("苹果用户")
                .country(dio.getCountry())
                .province(dio.getProvince())
                .city(dio.getCity())
                .build();
    }

    /**
     * 设置platInfo
     * @param dio
     * @param app
     * @param channelId
     * @return
     */
    private PlatInfo setPlatInfo(UserAuthLoginDIO dio, AppInfoDRO app, Integer channelId){
        return PlatInfo.builder()
                .shopId(dio.getShopId())
                .plat(app.getPlat())
                .channelId(channelId)
                .channelName(getNameByChannelId(channelId))
                .entrance(dio.getEntrance())
                .build();
    }

    /**
     * 设置UserAuthLoginInfo
     * @param app
     * @param info
     * @param platInfo
     * @return
     */
    private UserAuthLoginInfo setUserAuthLoginInfo(AppInfoDRO app, UserInfo info, PlatInfo platInfo){
        ThirdAppInfo thirdAppInfo = ThirdAppInfo.builder()
                .appId(app.getThirdAppId())
                .appName(app.getName())
                .appSecret(app.getThirdAppSecret())
                .build();
        UserOtherInfo userOtherInfo = UserOtherInfo.builder()
                .build();
        return UserAuthLoginInfo.builder()
                .userInfo(info)
                .userOtherInfo(userOtherInfo)
                .platInfo(platInfo)
                .thirdAppInfo(thirdAppInfo)
                .userPhoneInfo(new UserPhoneInfo())
                .build();
    }
}
